﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myBoard.Framework.BO;
using myBoard.Framework.Web.Server;
using System.IO;
using System.Diagnostics;

namespace myBoard.Framework
{
    /// <summary>
    /// This class allows magnets to communicate with myBoard
    /// </summary>
    public static class Connector
    {
        public delegate void NotificationsRequestedHandler(List<Notification> notifications);
        public static event NotificationsRequestedHandler NotificationsRequested;
        public delegate void HideMyBoardRequestedHandler();
        public static event HideMyBoardRequestedHandler HideMyBoardRequested;
        public delegate void ShowMyBoardRequestedHandler();
        public static event ShowMyBoardRequestedHandler ShowMyBoardRequested;
        public delegate void MagnetDroppedHandler(IMagnet droppedMagnet);
        public delegate void MagnetClosedHandler(IMagnet droppedMagnet);
        public static event MagnetDroppedHandler MagnetDropped;
        public static event MagnetClosedHandler MagnetClosed;

        /// <summary>
        /// This method should only be called by myboard
        /// </summary>
        /// <param name="magnet"></param>
        public static void RaiseMagnetDroppedEvent(IMagnet magnet)
        {
            if (MagnetDropped != null)
                MagnetDropped(magnet);
        }

        /// <summary>
        /// This method should only be called by myboard
        /// </summary>
        /// <param name="magnet"></param>
        public static void RaiseMagnetClosedEvent(IMagnet magnet)
        {
            if (MagnetClosed != null)
                MagnetClosed(magnet);
        }        

        /// <summary>
        /// Tell myBoard to show a notification
        /// </summary>
        /// <param name="notification">Notification to show</param>
        public static void Notify(Notification notification)
        {
            List<Notification> notifications = new List<Notification>();
            notifications.Add(notification);
            Notify(notifications);
        }

        /// <summary>
        /// Tell myBoard to show a list of notifications
        /// </summary>
        /// <param name="notifications">Notifications to show</param>
        public static void Notify(List<Notification> notifications)
        {
            if (NotificationsRequested != null)
                NotificationsRequested(notifications);
        }

        /// <summary>
        /// Tell myBoard to show itself
        /// </summary>
        public static void ShowMyBoard()
        {
            if (ShowMyBoardRequested != null)
                ShowMyBoardRequested();
        }


        /// <summary>
        /// Tell myBoard to hide itself
        /// </summary>
        public static void HideMyBoard()
        {
            if (HideMyBoardRequested != null)
                HideMyBoardRequested();
        }

        public static class WebServer
        {
            private static HttpListener _listener;
            private static Dictionary<string,string> _responses;

            public static void StartWebServer()
            {
                if (_listener == null)
                {
                    _listener = HttpListener.Create(System.Net.IPAddress.Any, 8081);
                    _listener.RequestReceived += new EventHandler<RequestEventArgs>(Listener_RequestReceived);
                    _listener.Start(5);
                }
            }

            public static void SetResponse(string requestId, string response)
            {
                if (_listener == null)
                    throw new Exception("Web server not available");
                if (_responses == null)
                    _responses = new Dictionary<string, string>();
                _responses.Add(requestId, response);
                Debug.WriteLine(string.Format("Reponse set for http://localhost:8081/{0}", requestId));
            }

            static void Listener_RequestReceived(object source, RequestEventArgs args)
            {
                IHttpClientContext context = (IHttpClientContext)source;
                IHttpRequest request = args.Request;
                string req = request.Uri.AbsolutePath.Remove(0, 1);
                // Respond is a small convenience function that let's you send one string to the browser.
                // you can also use the Send, SendHeader and SendBody methods to have total control.

                if (_responses.ContainsKey(req))
                {
                    string response = _responses[req];
                    context.Respond(response);
                }
                else
                {
                    IHttpResponse response = request.CreateResponse(context);
                    StreamWriter writer = new StreamWriter(response.Body);
                    writer.WriteLine(string.Empty);
                    writer.Flush();
                    response.Send();
                }
                
                /*if (request.Uri.AbsolutePath == "/hello")
                {
                    //context.Respond(@"<script type=""text/javascript"" src=""http://cdn.widgetserver.com/syndication/subscriber/InsertWidget.js""></script><script>if (WIDGETBOX) WIDGETBOX.renderWidget('423172a9-aecb-45a0-b69e-45ce5ae34db5');</script><noscript>Get the <a href=""http://www.widgetbox.com/widget/facebooksupermario"">Super Mario Game</a> widget and many other <a href=""http://www.widgetbox.com/"">great free widgets</a> at <a href=""http://www.widgetbox.com"">Widgetbox</a>! Not seeing a widget? (<a href=""http://docs.widgetbox.com/using-widgets/installing-widgets/why-cant-i-see-my-widget/"">More info</a>)</noscript>");
                    context.Respond(@"<script src=""http://www.gmodules.com/ig/ifr?url=http://bejeweledg.googlecode.com/svn/trunk/bejeweled.xml&amp;synd=open&amp;w=320&amp;h=270&amp;title=Bejeweled&amp;border=%23ffffff%7C3px%2C1px+solid+%23999999&amp;output=js""></script>");
                }

                else if (request.UriParts.Length == 1 && request.UriParts[0] == "goodbye")
                {
                    IHttpResponse response = request.CreateResponse(context);
                    StreamWriter writer = new StreamWriter(response.Body);
                    writer.WriteLine("Goodbye to you too!");
                    writer.Flush();
                    response.Send();
                }*/
            }
        }
    }
}
